package core

import (
	"context"
	"encoding/json"
	"fmt"
	"suitbim.com/media/utils"

	"github.com/gorilla/websocket"
)

// var wsConn *websocket.Conn
var err error

type Signer struct {
	manager *Manager
	wsConn  *websocket.Conn
	ctx     context.Context
	cancel  context.CancelFunc
}

func NewSigner(manager *Manager) *Signer {
	ctx, cancel := context.WithCancel(manager.ctx)
	return &Signer{
		manager: manager,
		ctx:     ctx,
		cancel:  cancel,
	}
}

// 连接到Dispatcher，准备接收来自Dispatcher发来的指令信号
func (s *Signer) listen() {
	c := G.Dispatcher.Signal
	url := fmt.Sprintf("ws://%s:%d", c.Host, c.Port)
	s.wsConn, _, err = websocket.DefaultDialer.Dial(url, nil)
	if err != nil {
		G.Log.Error("Can not connect to Dispatcher's Signer because: ", err)
		// 连不上Dispatcher时，通知Manager，由Manger决定如何处理
		s.manager.OnSignerDisconnected()
		return
	}
	G.Log.Infof("Connected to Dispatcher's Signer[%s]", url)
	for {
		select {
		case <-s.manager.ctx.Done():
			return
		default:
			_, data, err := s.wsConn.ReadMessage()
			if err != nil {
				G.Log.Error("Pusher Manager lose the connect to Dispatcher", err)
				s.listen()
				return
			}
			msg := Message{}
			json.Unmarshal(data, &msg)
			go s.manager.OnMessage(msg)
		}
	}
}

// SendSignal 发送消息到通信服务端
func (s *Signer) SendSignal(msg *Message) {
	err = s.wsConn.WriteMessage(websocket.BinaryMessage, []byte(utils.Struct2JsonString(*msg)))
	if err != nil {
		G.Log.Errorf("Send websocket fail：[%s]", err.Error())
		return
	}
}

// 定时发送轮询请求，查看当前还有哪些活跃的通道
// func (o *Signer) pollActivityChannels(ctx context.Context, d time.Duration) {
// 	tiker := time.NewTicker(d)
// 	for {
// 		<-tiker.C
// 		G.Log.Debug("pollActivityChannels")
// 		err := o.wsConn.WriteJSON(JSON{"method": "getActives", "param": JSON{}})
// 		if err != nil {
// 			G.Log.Error(err)
// 		}
// 	}

// }
